package com.zhiche.lisa.bms.controller.statistics;


import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.zhiche.lisa.bms.pojo.bo.statistics.OrderWaybillBO;
import com.zhiche.lisa.bms.pojo.vo.statistics.OrderWaybillQueryVO;
import com.zhiche.lisa.bms.pojo.vo.statistics.OrderWaybillVO;
import com.zhiche.lisa.bms.pojo.vo.statistics.WaybillCompositeVO;
import com.zhiche.lisa.bms.service.statistics.StaticWaybillCompositeService;
import com.zhiche.lisa.bms.service.utils.common.Cache;
import com.zhiche.lisa.bms.service.utils.common.ExcelCommon;
import com.zhiche.lisa.bms.service.utils.common.ExcelUtil;
import com.zhiche.lisa.bms.service.utils.common.MD5Util;
import com.zhiche.lisa.bms.utils.ToolCommonUtils;
import com.zhiche.lisa.core.enums.CommonEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 统计分析 前端控制器
 * </p>
 *
 * @author liangpeng
 * @since 2019-01-20
 */
@RestController
@RequestMapping("/statistics")
@Api(value = "/statistics", description = "统计分析接口", tags = {"统计分析接口"})
public class StatisticsController {
    private final Logger LOGGER = LoggerFactory.getLogger(StatisticsController.class);

    @Autowired
    private StaticWaybillCompositeService staticWaybillCompositeService;

    private Cache<SXSSFWorkbook> RESOURCES = new Cache<>();


    @PostMapping(value = "/getOrderWaybillDetail")
    @ApiOperation(value = "根据条件查询运单收入成本明细", notes = "根据条件查询运单收入成本明细", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = OrderWaybillVO.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<Page<OrderWaybillVO>> getOrderWaybillDetail(@RequestBody Page<OrderWaybillBO> page) {
        LOGGER.info("StatisticsController.getStaPricePage Param {} ", page);
        RestfulResponse<Page<OrderWaybillVO>> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        try {
            Page<OrderWaybillVO> pageVO = staticWaybillCompositeService.getOrderWaybillDetail(page);
            restful.setData(pageVO);
        } catch (BaseException e) {
            LOGGER.error("StatisticsController.getStaPricePage ERROR: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("StaPriceController.getStaPricePage ERROR: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return restful;
    }

    @PostMapping(value = "/getExportKey")
    @ApiOperation(value = "导出条件查询运单收入成本明细", notes = "导出条件查询运单收入成本明细", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses({@ApiResponse(code = 0, message = "success", response = OrderWaybillVO.class), @ApiResponse(code = -1, message = "系统异常")})
    public RestfulResponse<String> getExportKey(@RequestBody OrderWaybillQueryVO queryVO) {
        JwtAccountVO account = AccountUtil.getAccountInfoFromSecurityContext();
        LOGGER.info("StatisticsController.getExportKey Param {} , userName: {}", queryVO, account.getUsername());
        RestfulResponse<String> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);

        try {
            Map<String, Object> orderWaybillMapping = null;
            if ("1".equals(queryVO.getExportType())) {
                // 财务开票
                orderWaybillMapping = staticWaybillCompositeService.getOrderWaybillDataMap();
                orderWaybillMapping.put("invoiceDateYearMonth", "开票年月");
                orderWaybillMapping.put("receiptInvoiceDateType", "财务状态");
            } else if ("2".equals(queryVO.getExportType())) {
                // 财务收票
                orderWaybillMapping = staticWaybillCompositeService.getOrderWaybillDataMap();
                orderWaybillMapping.put("invoiceDateYearMonth", "开票年月");
                orderWaybillMapping.put("invoiceDateType", "财务状态");
            } else {
                // 普通
                orderWaybillMapping = staticWaybillCompositeService.getOrderWaybillDataMap();
            }

            List<String> mapVal = ExcelCommon.getMapVal(orderWaybillMapping);
            String[] titles = mapVal.toArray(new String[mapVal.size()]);
            // 查询导出数据
            List<OrderWaybillVO> list = staticWaybillCompositeService.queryOrderWaybillDetail(queryVO);

            //排除格式的字段
            List<String> excludes = staticWaybillCompositeService.getExcludeList();

            // 导出
            // HSSFWorkbook excel = ExcelUtil.export("导出运单收入成本明细", titles, list, orderWaybillMapping, excludes);
            SXSSFWorkbook excel = ExcelUtil.exportSXSSWorkExcel("导出运单收入成本明细", titles, list, orderWaybillMapping, excludes);
            String key = MD5Util.backMD5(excel.toString());
            key += "_FT11";
            RESOURCES.put(key, excel);
            restful.setData(key);
        } catch (BaseException e) {
            LOGGER.error("StatisticsController.getExportKey ERROR: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), e.getMessage(), null);
        } catch (Exception e) {
            LOGGER.error("StaPriceController.getExportKey ERROR: {}", e.getMessage());
            restful = new RestfulResponse(CommonEnum.ERROR.getCode(), CommonEnum.ERROR.getText(), null);
        }
        return restful;
    }

    @ApiOperation(value = "导出资源文件", notes = "导出资源账单", httpMethod = "GET")
    @GetMapping("/exportResource")
    public RestfulResponse<String> exportResouce(@RequestParam String key, HttpServletResponse response) throws IOException {
        if (Strings.isNullOrEmpty(key)) {
            return new RestfulResponse<>(CommonEnum.ERROR.getCode(), "文件key接收异常", null);
        }
        RestfulResponse<String> restful = new RestfulResponse<>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), null);
        //获取缓冲区数据资源
        SXSSFWorkbook excel = RESOURCES.get(key);
        if (Objects.isNull(excel)) {
            //未获取到资源抛出提示
            restful = new RestfulResponse<>(CommonEnum.ERROR.getCode(), "资源文件不存在", null);
        } else {
            String fileName = "订单收入成本明细_" + new DateTime().toString(ToolCommonUtils.yyyyMMddHHmm);
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            RESOURCES.remove(key);
            LOGGER.info("DownloaExlFile:" + key);
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
            OutputStream ouputStream = response.getOutputStream();
            excel.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        }
        return restful;
    }


    /**
     * 成本缺失明细导出
     *
     * @return
     */
    @ApiOperation(value = "成本缺失明细导出", notes = "成本缺失明细导出", httpMethod = "POST")
    @PostMapping("/exportCostMissingDetailExcel")
    public RestfulResponse<String> exportCostMissingDetailExcel() {
        Map<String, Object> costMissingDetailMap = staticWaybillCompositeService.getCostMissingDetailExportMap();
        List<String> mapVal = ExcelCommon.getMapVal(costMissingDetailMap);
        String[] titles = mapVal.toArray(new String[mapVal.size()]);
        List<WaybillCompositeVO> voList = staticWaybillCompositeService.getCostMissingDetail();
        // 导出组装
        SXSSFWorkbook excel = ExcelUtil.exportSXSSWorkExcel("_成本缺失明细导出", titles, voList, costMissingDetailMap, Lists.newArrayList());
        String key = MD5Util.backMD5(excel.toString());
        if (!StringUtils.isEmpty("_成本缺失明细导出")) {
            key += "_成本缺失明细导出";
        }
        RESOURCES.put(key, excel);
        return new RestfulResponse<String>(CommonEnum.SUCCESS.getCode(), CommonEnum.SUCCESS.getText(), key);
        // 导出Excel
        //return baseExcelController.commonExportExcelResult("_成本缺失明细导出", titles, voList, costMissingDetailMap, "_成本缺失明细导出");
    }
}

